﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace 启动服务
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("参数错误，未指定服务名，无法启动！！！");
                Console.ReadKey();
            }

            string serviceName = args[0];
            _ = bool.TryParse(args.Length >= 2 ? args[1] : "true", out bool autoClose);

            //获得服务集合
            ServiceController[] serviceControllers = ServiceController.GetServices();
            var server = serviceControllers.FirstOrDefault(service => service.ServiceName.Equals(serviceName) || service.DisplayName.Equals(serviceName));
            if (server == null)
            {
                Console.WriteLine("未能找到服务:{0}", serviceName);
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("已找到服务:{0}", serviceName);

                if (server.Status != ServiceControllerStatus.Running)
                {
                    Console.WriteLine("服务:{0}，准备运行。", serviceName);
                    server.Start();
                    Console.WriteLine("服务:{0}，已运行。", serviceName);
                }
                else
                {
                    Console.WriteLine("服务:{0}，已在运行中，无需再次运行。", serviceName);
                }
            }

            if (!autoClose)
            {
                Console.ReadKey();
            }

        }
    }
}
